/*
 * Copyright (c) 2020 pig4cloud Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.pig4cloud.pig.codegen.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pig.codegen.entity.GenConfig;
import com.pig4cloud.pig.codegen.service.GeneratorService;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import mix.codegen.common.config.DataSourceProperties;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 代码生成器
 *
 * @author lengleng
 * @date 2018-07-30
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/generator")
@Api(value = "generator", tags = "代码生成模块")
public class GeneratorController {

    private final GeneratorService generatorService;

    /**
     * 生成代码
     */
    @SneakyThrows
    @GetMapping("/code")
    public void generatorCode(HttpServletResponse response) {

        List<String> tableList=new ArrayList<>();
        Page<Map<String, Object>> mapPage = (Page<Map<String, Object>>) generatorService.getPage(Page.of(1, 9999), "");
        if (CollUtil.isNotEmpty(mapPage.getRecords())) {
            mapPage.getRecords().forEach(m -> {
                tableList.add(m.get("tableName").toString());
            });

        }
        if(CollUtil.isNotEmpty(tableList)) {
            byte[] data = generatorService.generatorCode(tableList);
            response.reset();
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
                    String.format("attachment; filename=%s.zip", tableList.get(0)));
            response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
            response.setContentType("application/octet-stream; charset=UTF-8");

            IoUtil.write(response.getOutputStream(), Boolean.TRUE, data);
        }
    }

}
